﻿Public Class Chat

    Private Shared _lock As System.Threading.EventWaitHandle

    Shared Sub New()
        _lock = New System.Threading.ManualResetEvent(False)
    End Sub

    Public Class User
        Property ID As Long
        Property Name As String
        Property IsAdmin As Boolean

        Private UserName As String
        Private Password As String

        Shared Function ListUsers() As List(Of Chat.User)
            Dim userFilePath = HttpContext.Current.Server.MapPath("~/data/users.xml")

            Dim fileContent = System.IO.File.ReadAllText(userFilePath)

            Dim u = System.Xml.Linq.XElement.Parse(fileContent)

            Dim ooo = (From t In u...<user>
                      Select New Chat.User With {.ID = t.@id,
                                                 .Name = t...<name>.Value,
                                                 .IsAdmin = t...<isadmin>.Value,
                                                 .UserName = t...<username>.Value,
                                                 .Password = t...<password>.Value}).ToList

            Return ooo
        End Function


        Shared Function GetUserByID(ByVal userID As Long) As Chat.User

            
            Dim obj = (From t In ListUsers() Where t.ID = userID Select t).FirstOrDefault


            Return obj


        End Function

        Shared Function Authenticate(ByVal userName As String, ByVal password As String) As User
            Dim o = (From t In ListUsers() Where t.UserName = userName AndAlso t.Password = password Select t).firstordefault
            Return o
            'If userName = "admin" AndAlso password = "admin" Then
            '    Dim o As New Chat.User
            '    o.IsAdmin = True
            '    o.Name = userName
            '    o.ID = Now.Ticks
            '    Return o
            'ElseIf userName = "user" AndAlso password = "user" Then
            '    Dim o As New Chat.User
            '    o.Name = userName
            '    o.ID = Now.Ticks
            '    Return o
            'Else
            '    Return Nothing
            'End If

        End Function

    End Class

    Public Class Message
        Property ID As Long
        Property Content As String
        Property User As Chat.User
        Property SentAt As Date
        Sub New()
            Me.ID = Now.Ticks
            Me.SentAt = Now
        End Sub
    End Class

    Shared Sub PostChat(ByVal message As String, ByVal fromUserID As Long)
        Dim objUser As User = Chat.User.GetUserByID(fromUserID)
        If objUser IsNot Nothing Then
            Dim objMessage As New Message
            objMessage.ID = Now.Ticks
            objMessage.Content = message
            objMessage.User = objUser

            Dim xmlToWrite = <message id=<%= Now.Ticks %>>
                                 <content><%= message %></content>
                                 <sentat><%= Now.Ticks %></sentat>
                                 <user>
                                     <id><%= fromUserID %></id>
                                     <name><%= objUser.Name %></name>
                                 </user>
                             </message>

            Dim pathToSave = HttpContext.Current.Server.MapPath("~/data/chat.xml")

            System.IO.File.AppendAllText(pathToSave, xmlToWrite.ToString)

            _lock.Set()
            _lock.Reset()

        End If

    End Sub

    Shared Function ListChats() As List(Of Chat.Message)
        Dim fileToRead = HttpContext.Current.Server.MapPath("~/data/chat.xml")
        Dim fileContent = System.IO.File.ReadAllText(fileToRead)

        Dim xml = System.Xml.Linq.XElement.Parse("<x>" & fileContent & "</x>")

        Dim objChats = (From t In xml...<message>
                        Select New Chat.Message With {.ID = t.@id,
                                                      .Content = t...<content>.Value,
                                                      .SentAt = DateTime.FromBinary(t...<sentat>.Value),
                                .User = New Chat.User With {.ID = t...<user>...<id>.Value,
                                                .Name = t...<user>...<name>.Value}}).ToList

        Return objChats

    End Function

    Shared Function GetChats(ByVal lastChatRecivedID As Long) As List(Of Chat.Message)

        Dim fileToRead = HttpContext.Current.Server.MapPath("~/data/chat.xml")
        Dim fileContent = System.IO.File.ReadAllText(fileToRead)

        Dim xml = System.Xml.Linq.XElement.Parse("<x>" & fileContent & "</x>")

        Dim objChats = (From t In ListChats()
                       Where t.ID > lastChatRecivedID).ToList
                       
        If objChats.Count = 0 Then
            Dim o As New List(Of Threading.EventWaitHandle)
            o.Add(_lock)

            Threading.WaitHandle.WaitAny(o.ToArray)

            objChats = (From t In ListChats()
                       Where t.ID > lastChatRecivedID).ToList

        End If

        Return objChats

    End Function

    'Public Class ChatMessageEventArgs
    '    Inherits EventArgs
    '    Property FromUserID As Long
    '    Property Message As String

    'End Class
End Class

